package org.dzl.springboot001.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.dzl.springboot001.config.JSONResult;
import org.dzl.springboot001.dao.NewsDao;
import org.dzl.springboot001.entity.News;
import org.dzl.springboot001.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 光的代言人
 */
@Slf4j
@RestController
@RequestMapping("news")
public class NewsController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private NewsDao newsDao;
    @GetMapping("show")
    public JSONResult show(Integer id){
        News news=null;
        long start = System.currentTimeMillis();
        // 规定，每条新闻在redis中以id为key，新闻为value
        //首先到redis中查找对应id的信息，如果有就直接返回，如果没有就到数据库中查找，并把结果存到redis中，下一次查询就直接返回redis中的数据，这样以来查询速度快很多
        String result=redisService.getString("news."+id);
        log.error("result:"+result);
        if(result==null){
            news=newsDao.getNewsById(id);
            redisService.setString("news."+id, JSON.toJSONString(news));
        }else{
            //把JSON字符串转成news对象
            news=JSON.parseObject(result,News.class);
        }
        long end = System.currentTimeMillis();
        log.info("查询耗时："+(end-start)+"ms");
        return new JSONResult(news);
    }
}
